package com.metaera.app.ui.popup;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.lxj.xpopup.impl.FullScreenPopupView;
import com.lxj.xpopup.util.XPopupUtils;
import com.metaera.app.MetaEraApplication;
import com.metaera.app.R;
import com.metaera.app.data.model.ProfileResponse;
import com.metaera.app.data.network.ApiParam;
import com.metaera.app.utils.DateUtils;
import com.metaera.app.utils.ToastUtils;
import com.metaera.app.utils.image.GlideApp;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;

import androidx.annotation.NonNull;

import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * 个人主页的分享
 */
public class ShareUserProfilePopup extends FullScreenPopupView {

    private ProfileResponse mResponse;

    public ShareUserProfilePopup(@NonNull Context context) {
        super(context);
    }

    public ShareUserProfilePopup(@NonNull Context context, ProfileResponse response) {
        super(context);
        mResponse = response;
    }

    @Override
    protected int getImplLayoutId() {

        return R.layout.popup_share_user_profile;
    }

    @Override
    protected void initPopupContent() {
        super.initPopupContent();
        ViewGroup layoutContainer = findViewById(R.id.layout_container);
        XPopupUtils.applyPopupSize(
                layoutContainer,
                (int) (XPopupUtils.getAppWidth(getContext()) * 0.85f),
                getMaxHeight(),
                getPopupWidth(),
                getPopupHeight(),
                null
        );
    }


    @Override
    protected void onCreate() {
        super.onCreate();
        Resources resources = getContext().getResources();

        TextView tvTitle = findViewById(R.id.tv_news_title);
        TextView tvDate = findViewById(R.id.tv_date);
        ImageView ivAvatar = findViewById(R.id.iv_avatar);
        TextView tvNickname = findViewById(R.id.tv_nickname);
        TextView tvSignature = findViewById(R.id.tv_signature);
        TextView tvFansNumber = findViewById(R.id.tv_fans_number);
        TextView tvArticleNumber = findViewById(R.id.tv_article_number);

        findViewById(R.id.button_cancel).setOnClickListener(v -> dismiss());
        findViewById(R.id.tv_wechat).setOnClickListener(v -> share2WX());
        findViewById(R.id.tv_moments).setOnClickListener(v -> share2Friend());

        findViewById(R.id.tv_link).setOnClickListener(v -> {
            dismiss();

            ClipboardManager cm = (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);
            cm.setPrimaryClip(ClipData.newPlainText("Simple text", ApiParam.LINK_SHARE_6 + mResponse.getId()));
            ToastUtils.makeText("复制成功");
        });

        tvNickname.setText(mResponse.getNickname());
        tvArticleNumber.setText(mResponse.getActivity_num() + resources.getString(R.string.article_number_placeholder));
        if (!TextUtils.isEmpty(mResponse.getDesc())) {
            tvSignature.setText(mResponse.getDesc());
        }

        ProfileResponse.NewActivity new_activity = mResponse.getNew_activity();
        if (new_activity != null){
            tvTitle.setText(new_activity.getTitle());
            tvDate.setText(DateUtils.getTime(new_activity.getRelease_time_stamp(), DateUtils.PATTERN_2));
        } else {

            View layoutDate = findViewById(R.id.layout_date);
            tvTitle.setVisibility(View.GONE);
            layoutDate.setVisibility(View.GONE);

        }

        tvFansNumber.setText(mResponse.getFans_num() + resources.getString(R.string.fans));
        GlideApp.with(ivAvatar).load(mResponse.getAvatar_img()).avatar().into(ivAvatar);
    }


    // 分享至微信
    private void share2WX() {
        if (!MetaEraApplication.sWxApi.isWXAppInstalled()) {
            ToastUtils.makeText("您还未安装微信客户端");

        } else {
            share2WX(SendMessageToWX.Req.WXSceneSession);
        }
    }


    // 分享至朋友圈
    private void share2Friend() {
        if (!MetaEraApplication.sWxApi.isWXAppInstalled()) {
            ToastUtils.makeText("您还未安装微信客户端");

        } else {
            share2WX(SendMessageToWX.Req.WXSceneTimeline);
        }

        dismiss();
    }

    // 分享到微信
    private void share2WX(int scene) {
//        try {
            // title, desc, link, image

            WXWebpageObject wxWebpageObject = new WXWebpageObject();
            wxWebpageObject.webpageUrl = ApiParam.LINK_SHARE_6 + mResponse.getId(); // 链接
            WXMediaMessage wxMediaMessage = new WXMediaMessage(wxWebpageObject);
            wxMediaMessage.title = mResponse.getNickname() + "的个人主页"; // 标题
            wxMediaMessage.description = ""; // 描述

            // 图片

//            if (drawableId != 0){
                wxMediaMessage.setThumbImage(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

//            } else if (imageLink != null){
//                Bitmap thumb = BitmapFactory.decodeStream(new URL("mShareModel.imageUrl").openStream());
//                Bitmap thumbBmp = Bitmap.createScaledBitmap(thumb, 120, 150, true);
//                ByteArrayOutputStream stream = new ByteArrayOutputStream();
//                thumbBmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//                wxMediaMessage.thumbData = stream.toByteArray(); // 图片
//                thumb.recycle();
//            }

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.scene = scene;
            req.message = wxMediaMessage;
            req.transaction = String.valueOf(System.currentTimeMillis());
            MetaEraApplication.sWxApi.sendReq(req);

//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
            dismiss();
//        }
    }
}
